package com.hjb.service.controller.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hjb.service.annotation.LogInfo;
import com.hjb.service.annotation.LogType;
import com.hjb.service.app.BaseAreaService;
import com.hjb.service.app.BrokerUserService;
import com.hjb.service.app.SiteCompanyService;
import com.hjb.service.com.ComLogInfoService;
import com.hjb.service.com.ComVerifyCodeService;
import com.hjb.service.config.constant.ComLogInfoConstant;
import com.hjb.service.config.constant.ComVerifyCodeConstant;
import com.hjb.service.config.constant.Constants;
import com.hjb.service.config.constant.EnumCode;
import com.hjb.service.config.constant.Key;
import com.hjb.service.domain.BaseArea.Area;
import com.hjb.service.domain.BaseArea.BaseArea;
import com.hjb.service.domain.SiteCompany.SiteCompany;
import com.hjb.service.domain.brokerUser.BrokerUser;
import com.hjb.service.domain.comloginfo.ComLogInfo;
import com.hjb.service.utils.MD5Utils;
import com.hjb.service.utils.MapUtil;
import com.hjb.service.utils.RequestUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/** 
* @ClassName    : UserController 
* @author       : panxingwu 
* @date         : 2018年1月6日 下午5:18:15 
* @Description  : 用户相关接口
*/
@RestController
@RequestMapping("/app/user")
@Api(value="/app/user",description="APP端用户接口")
public class AppUserController {
	private Logger log = LoggerFactory.getLogger(AppUserController.class);
	
	@Autowired
	private BrokerUserService brokerUserService;
	
	@Autowired
	private ComLogInfoService comLogInfoService;
	@Autowired
	private BaseAreaService baseAreaService;
	
	@Autowired
	private ComVerifyCodeService comVerifyCodeService;
	@Autowired
	private SiteCompanyService siteCompanyService;
	
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	
	@LogInfo(logType=LogType.查询,operationContent="用户登录")
	@PostMapping("login")
	@ResponseBody
	@ApiOperation("用户登录")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "loginName", value = "登录名", required = true,defaultValue="13888888888"), 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "loginPassword", value = "登录密码", required = true,defaultValue="111111"), 
		})
	public ResponseEntity login(HttpServletRequest request,
	        @RequestParam(value = "loginName",required = false)String loginName,
	        @RequestParam(value = "loginPassword",required = false)String loginPassword){
		Map<String, Object> result = MapUtil.getRetMap();
		Map<String, Object> data = new HashMap<String, Object>();
		
		//登录名为空
		if (StringUtils.isBlank(loginName)) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_401);
			result.put(Key.RESULT_INFO, "用户名为空");
			return ResponseEntity.ok(result);
		}
		
		//密码为空
		if (StringUtils.isBlank(loginPassword)) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_402);
			result.put(Key.RESULT_INFO, "密码为空");
			return ResponseEntity.ok(result);
		}
		List<BrokerUser> brokerUserList = brokerUserService.getBrokerUser(loginName, loginPassword);
		//用户名或密码错误
		if (brokerUserList == null || brokerUserList.size()==0) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_403);
			result.put(Key.RESULT_INFO, "用户名或密码错误");
			return ResponseEntity.ok(result);
		}
		BrokerUser brokerUser = brokerUserList.get(0);
		String ip = RequestUtil.getRemoteAddr(request);
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				//登录记录
				ComLogInfo comLogInfo = new ComLogInfo();
				comLogInfo.setUserId(brokerUser.getId().longValue());
				comLogInfo.setEventType(ComLogInfoConstant.EVENT_TYPE.login.getType());
				comLogInfo.setSuccess(ComLogInfoConstant.SUCCESS.YES.getCode());
				comLogInfo.setDescription("成功");
				comLogInfo.setOperateTime(new Date());
				comLogInfo.setChannel(ComVerifyCodeConstant.CodeChannel.web.getV());
				comLogInfo.setIp(ip);
				comLogInfoService.insertComLogInfo(comLogInfo);
			}
		});
		//获取配置信息
		SiteCompany siteCompany = new SiteCompany();
		siteCompany.setBrokerUserId(brokerUser.getId()+"");
		SiteCompany siteCompanyResult = siteCompanyService.getSiteCompanyByUserId(siteCompany);
		
		//获取省市区信息
		List<BaseArea> areas = baseAreaService.getTopParents();
		List<Area> areaList = this.getArea(areas);
		for (Iterator iterator = areaList.iterator(); iterator.hasNext();) {
			Area area = (Area) iterator.next();
			List<BaseArea> subBaseAreas = baseAreaService.getBaseAreasByParentId(area.getId());
			List<Area> subAreaList = this.getArea(subBaseAreas);
			//第三级遍历
			for (Iterator iterator2 = subAreaList.iterator(); iterator2.hasNext();) {
				Area subArea = (Area) iterator2.next();
				List<BaseArea> subSubBaseAreas = baseAreaService.getBaseAreasByParentId(subArea.getId());
				subArea.setSubAreas(this.getArea(subSubBaseAreas));
			}
			area.setSubAreas(subAreaList);
		}
		
		request.getSession().setAttribute(Key.BROKERUSER, brokerUser);
		brokerUser.setPassword("");
		data.put(Key.USER, brokerUser);
		data.put(Key.AREA, areaList);
		//加工服务费承担方式
		String[] feeReceiveArray = siteCompanyResult.getFeeReceive().split(",");
		List<Map<String,String>> feeReceiveList = new ArrayList<Map<String,String>>();
		for (int i = 0; i < feeReceiveArray.length; i++) {
			Map<String,String> feeReceive = new HashMap<String,String>();
			String[] subArray = feeReceiveArray[i].split("\\|");
			feeReceive.put(Key.VALUE, subArray[0]);
			feeReceive.put(Key.LABLE, subArray[1]);
			feeReceiveList.add(feeReceive);
		}
		data.put(Key.FEERECEIVE,feeReceiveList);//服务费承担方
		
		//加工付款方式
		String[] payTypeArray = siteCompanyResult.getRemark().split(",");
		List<Map<String,String>> payTypeList = new ArrayList<Map<String,String>>();
		for (int i = 0; i < payTypeArray.length; i++) {
			Map<String,String> payTyepe = new HashMap<String,String>();
			String[] subArray = payTypeArray[i].split("\\|");
			payTyepe.put(Key.VALUE, subArray[0]);
			payTyepe.put(Key.LABLE, subArray[1]);
			payTypeList.add(payTyepe);
		}
		data.put(Key.PAYTYPE, payTypeList);//付款方式
		
		//首付方式
		String[] firstPayTypeArray = siteCompanyResult.getFirstPayType().split(",");
		List<Map<String,String>> firstPayTypeList = new ArrayList<Map<String,String>>();
		for (int i = 0; i < firstPayTypeArray.length; i++) {
			Map<String,String> firstPayTyepe = new HashMap<String,String>();
			String[] subArray = firstPayTypeArray[i].split("\\|");
			firstPayTyepe.put(Key.VALUE, subArray[0]);
			firstPayTyepe.put(Key.LABLE, subArray[1]);
			firstPayTypeList.add(firstPayTyepe);
		}		
		data.put(Key.FIRSTPAYTYPE,firstPayTypeList);//首付方式
		
		//租住方式
		List<Map<String,String>> rentTypeList = new ArrayList<Map<String,String>>();
		Map<String,String> rentType = new HashMap<String,String>();
		rentType.put(Key.LABLE, "整租");
		rentType.put(Key.VALUE, "1");
		Map<String,String> rentType2 = new HashMap<String,String>();
		rentType2.put(Key.LABLE, "合租");
		rentType2.put(Key.VALUE, "2");
		rentTypeList.add(rentType);
		rentTypeList.add(rentType2);
		data.put(Key.RENTTYPE, rentTypeList);
		
		result.put(Key.DATA, data);
		result.put(Key.RESULT_CODE, MapUtil.INTF_SUC_CODE);
		result.put(Key.RESULT_INFO, "登录成功");
		return ResponseEntity.ok(result);
	}
	
	@LogInfo(logType=LogType.查询,operationContent="是否登录")
	@PostMapping("is_login")
	@ResponseBody
	@ApiOperation("判断用户是否登录")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "userId", value = "用户ID", required = true,defaultValue="100000"), 
		})
	public ResponseEntity isLogin(HttpServletRequest request){
		Map<String, Object> result = MapUtil.getRetMap();
		Map<String, Object> data = new HashMap<String, Object>();
		
		String isLogin = Constants.NO;
		BrokerUser brokerUesr = (BrokerUser) request.getSession().getAttribute(Key.BROKERUSER);
		//会话过期
		if (brokerUesr != null) {
			isLogin = Constants.YES;
		}
		data.put("isLogin", isLogin);
		result.put("data", data);
		result.put(Key.RESULT_CODE, EnumCode.SUCCESS.getCode());
		result.put(Key.RESULT_INFO, EnumCode.SUCCESS.getDesc());
		return ResponseEntity.ok(result);
	}

	@LogInfo(logType=LogType.查询,operationContent="修改密码")
	@PostMapping("modPassword")
	@ResponseBody
	@ApiOperation("修改密码")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "loginName", value = "登录名", required = true,defaultValue="13888888888"), 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "oldPassword", value = "旧密码", required = true,defaultValue="111111"), 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword", value = "新密码", required = true,defaultValue="222222"), 
		})
	public ResponseEntity modPassword(HttpServletRequest request,
	        @RequestParam(value = "loginName",required = false)String loginName,
	        @RequestParam(value = "oldPassword",required = false)String oldPassword,
	        @RequestParam(value = "newPassword",required = false)String newPassword){
		Map<String, Object> result = MapUtil.getRetMap();
		Map<String, Object> data = new HashMap<String, Object>();
		
		String isLogin = Constants.NO;
		//登录名为空
		if (StringUtils.isBlank(loginName)) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_401);
			result.put(Key.RESULT_INFO, "用户名为空");
			return ResponseEntity.ok(result);
		}
		
		//密码为空
		if (StringUtils.isBlank(oldPassword)) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_402);
			result.put(Key.RESULT_INFO, "密码为空");
			return ResponseEntity.ok(result);
		}
		//密码为空
		if (StringUtils.isBlank(newPassword)) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_411);
			result.put(Key.RESULT_INFO, "新密码为空");
			return ResponseEntity.ok(result);
		}
		List<BrokerUser> brokerUserList = brokerUserService.getBrokerUser(loginName, oldPassword);
		//用户名或密码错误
		if (brokerUserList == null || brokerUserList.size()==0) {
			result.put(Key.RESULT_CODE, MapUtil.INTF_ERR_CODE_403);
			result.put(Key.RESULT_INFO, "用户名或密码错误");
			return ResponseEntity.ok(result);
		}
		BrokerUser brokerUser = new BrokerUser();
		brokerUser.setPassword(MD5Utils.encrypt(newPassword));
		brokerUser.setLoginName(loginName);
		brokerUserService.updatePassword(brokerUser);
		
		request.getSession().invalidate();//变更密码后退出登录
		data.put("isLogin", Constants.NO);
		result.put("data", data);
		result.put(Key.RESULT_CODE, EnumCode.SUCCESS.getCode());
		result.put(Key.RESULT_INFO, EnumCode.SUCCESS.getDesc());
		return ResponseEntity.ok(result);
	}	
	/** 
	* @Title      :loginOut 
	* @param      :@param request
	* @param      :@return 
	* @return     :Object 
	* @throws     :
	* @Description: 退出登录
	*/
	@LogInfo(logType=LogType.新增,operationContent="退出登录")
	@PostMapping("loginOut")
	@ApiOperation("退出登录")
	@ResponseBody
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "query", dataType = "String", name = "userId", value = "用户ID", required = true,defaultValue="100000"), 
		})
	public ResponseEntity loginOut(HttpServletRequest request){
		Map<String, Object> result = MapUtil.getRetMap();
		request.getSession().invalidate();
		result.put(Key.RESULT_CODE,EnumCode.SUCCESS.getCode());
		result.put(Key.RESULT_INFO,EnumCode.SUCCESS.getDesc());
		result.put(Key.DATA, "loginOut");
		return ResponseEntity.ok(result);
	}
	
	
	private List<Area> getArea(List<BaseArea> baseAreas){
		List<Area> list =  new ArrayList<Area>();
		for (Iterator iterator = baseAreas.iterator(); iterator.hasNext();) {
			BaseArea baseArea = (BaseArea) iterator.next();
			Area area = new Area();
			area.setId(baseArea.getId());
			area.setName(baseArea.getName());
			list.add(area);
		}
		return list;
	}
}
